<template>
	<view class="my-box-container flex flex-column">
		<Nav id="nav" :bgColor="bgColor" title="我的开盒" @back="backToPerson"></Nav>
		<Tab id="tab" :tabs="tabs" :currentActive="currentActive" @tabChange="tabChange"></Tab>
		<swiper class="swiper" @change="swiperChange" :current="currentActive" :style="{height:swiperHeight}">
			<swiper-item v-for="(swiperItem,swiperIndex) in swiperList">
				<scroll-view scroll-y="true" class="scroll-view" v-if="swiperItem.list.length"
					@scrolltolower="api(swiperItem,'/api/member/boxlist')">
					<view class="box-list">
						<BoxItem :showCheckBox="swiperIndex==0" class="box-item" :value="item" :key="item.id"
							v-for="(item,index) in swiperItem.list" @boxItemSelect="boxItemSelect(item)"
							@preDetail="preDetail(item)">
						</BoxItem>
					</view>
					<ns-loading :isRotate="true" v-if="swiperItem.loading"></ns-loading>
					<view class="load-finish" v-if="swiperItem.finish">亲，已经到底了哦~</view>
				</scroll-view>
				<view class="empty-wrapper flex justify-center align-center flex-column" v-else>
					<text class="empty-icon"></text>
					<text class="empty-text">这里什么都没有哦~</text>
				</view>
			</swiper-item>
		</swiper>
		<view id="total-placeholder" class="total-container iphone-x flex flex-column" v-if="currentActive==0">
			<view class="free-limit flex align-center"
				v-if="$store.state.free_express &&swiperList[currentActive].list.length">
				<text class="label">限时</text>
				<text class="limit-value">满{{$store.state.free_express}}个免运费,7个工作日内发货</text>
			</view>
			<view class="flex justify-between align-center total-bottom">
				<view class="select-all flex align-center" @click="selectAll">
					<radio class="radio" color="#6E24FF" :checked="allSelect" />
					<text class="label">全选({{c_selectCount}})</text>
				</view>
				<view class="delivery-btn" @click="delivery">立即发货</view>
				<view class="recycling-btn" @click="showPopup">立即回收</view>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom">
			<recyclePop :value="recycleValue" @comfirmRecycle="comfirmRecycle" @closePop="closePop"
				@toDetail="toDetail"></recyclePop>
		</uni-popup>
		<uni-popup ref="detailShop" type="bottom">
			<shopDetail :value="shopDetailValue" @closePop="closeDetail"></shopDetail>
		</uni-popup>
		<uni-popup ref="freeExpressPopup" type="center">
			<view class="free-express-dialog">
				<text class="close-icon iconfont1 icon-guanbi1"></text>
				<view class="free-tip">提货满{{$store.state.free_express}}件商品可享免费哦！</view>
				<view class="flex justify-between align-center">
					<view class="think-more" @click="closeFree">我再想想</view>
					<view class="continue" @click="continueDelivery">继续提货</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import Nav from "@/components/magic-box/magic-nav/index.vue"
	import navMixin from "@/common/js/nav.js"
	import Tab from "@/components/magic-box/magic-tab/index.vue"
	import BoxItem from "./box_item.vue"
	import util from "@/common/js/util.js"
	import recyclePop from "@/components/magic-box/recycle-pop/index.vue"
	import pageApi from "@/common/js/pageApi.js"
	import shopDetail from "@/components/magic-box/shop-detail/index.vue"
	export default {
		mixins: [navMixin, pageApi],
		components: {
			Nav,
			Tab,
			BoxItem,
			recyclePop,
			shopDetail
		},
		data() {
			return {
				shopDetailValue: {
					sku_id: "",
					content: ""
				},
				recycleValue: {
					count: 0,
					totoalPrice: 0,
					calcPrice: 0
				},
				swiperHeight: "",
				allSelect: false,
				tabs: [{
					name: "待提货"
				}, {
					name: "待收货"
				}, {
					name: "已完成"
				}, {
					name: "已回收"
				}],
				currentActive: 0,
				swiperList: [{
					params: {
						type: 2,
						page: 0,
						page_size: 10,
					},
					loading: false,
					list: [],
					finish: false
				}, {
					params: {
						type: 3,
						page: 0,
						page_size: 10,
					},
					loading: false,
					list: [],
					finish: false
				}, {
					params: {
						type: 4,
						page: 0,
						page_size: 10,
					},
					list: [],
					loading: false,
					finish: false
				}, {
					params: {
						type: 5,
						page: 0,
						page_size: 10,
					},
					list: [],
					loading: false,
					finish: false
				}],
				backType: ""
			};
		},
		computed: {
			c_selectCount() {
				return this.swiperList[this.currentActive].list.filter(item => item.checked).length
			}
		},
		methods: {
			toDetail() {
				const list = this.$util.deepClone(this.swiperList[this.currentActive].list.filter(item => item.checked))
					.map(item => ({
						...item,
						back_amount:parseFloat(item.box_amount * this.$store.state.recovery.customer_recovery_rate).toFixed(2)
					}))

				const params = JSON.stringify(list)
				uni.navigateTo({
					url: '/pages/magic-box/draw-result/recycleDetail?list=' + params,
				})
			},
			closeDetail() {
				this.$refs.detailShop.close()
			},
			//查看商品详情
			async preDetail(item) {
				try {
					const result = await this.$api.sendRequest({
						url: "/api/fudai/goodsdetail",
						data: {
							sku_id: item.sku_id
						},
						async: false
					})
					this.shopDetailValue.sku_id = item.sku_id
					this.shopDetailValue.content = result.data.goods_content
					this.$refs.detailShop.open()
				} catch (e) {
					//TODO handle the exception
				}

			},
			backToPerson() {
				if (this.backType) {
					uni.switchTab({
						url: "../../pages/member/index/index"
					})
				} else {
					uni.navigateBack({
						delta: 1
					})
				}
			},
			closeFree(){
				this.$refs.freeExpressPopup.close()
			},
			delivery() {
				const list = this.swiperList[this.currentActive].list.filter(item => item.checked)
				if (!list.length) {
					uni.showToast({
						title: "请勾选要发货的商品",
						icon: "none"
					})
					return
				}
				if(list.length<this.$store.state.free_express){
					this.$refs.freeExpressPopup.open()
					return
				}
				this.continueDelivery()
				
			},
			continueDelivery(){
					const list = this.swiperList[this.currentActive].list.filter(item => item.checked)
					const cart_ids = list.map(item => item.id)
					this.$api.sendRequest({
						url: '/api/ordercreate/payment',
						data: {cart_ids,box:1},
						success: res => {
							if (res.code >= 0) {
								uni.setStorage({
									key: 'orderCreateData',
									data: {
										cart_ids: cart_ids.toString(),
									},
									success: () => {
										this.$refs.freeExpressPopup.close()
										this.$util.redirectTo('/pages/order/payment/payment?box=1');
									}
								});
							} else {
								uni.showToast({
									icon:"error",
									title:res.data.message
								})
							}
						},
						fail: res => {
							uni.showToast({
								icon:"error",
								title:res.data.message
							})
						}
					})
			},
			showPopup() {
				const list = this.swiperList[this.currentActive].list.filter(item => item.checked)
				if (!list.length) {
					uni.showToast({
						title: "请勾选要回收商品",
						icon: "none"
					})
					return
				}
				const totalPrice = list.reduce((pre, value) => (pre += parseFloat(value.box_amount)), 0)
				this.recycleValue.totoalPrice =parseFloat(totalPrice * this.$store.state.recovery.customer_recovery_rate).toFixed(2)
				this.recycleValue.count = this.c_selectCount
				this.recycleValue.calcPrice = parseFloat(totalPrice).toFixed(2)
				this.$refs.popup.open()
			},
			async comfirmRecycle() {
				try {
					const ids = this.swiperList[this.currentActive].list.filter(item => item.checked).map(item => item
						.id)
					console.log("id", ids)
					const result = await this.$api.sendRequest({
						header: {
							'content-type': 'application/json'
						},
						async: false,
						url: "/api/member/recovery",
						data: {
							ids
						}
					})
					if (result.data == "ok") {
						uni.showToast({
							title: result.message,
							icon: "success"
						})
						this.swiperList[this.currentActive].list = this.swiperList[this.currentActive].list.filter(
							item => !item.checked)
						//重置
						this.swiperList.slice(1).forEach(item => {
							item.list = []
							item.params = Object.assign({}, item.params, {
								page: 0
							})

							item.finish = false
						})
					} else {
						uni.showToast({
							title: result.message,
						})
					}

				} catch (e) {
					//TODO handle the exception
				}
				this.$refs.popup.close()
			},
			closePop() {
				this.$refs.popup.close()
			},
			tabChange(index) {
				if (this.currentActive == index) {
					return
				}
				this.currentActive = index
			},
			//全选
			selectAll() {
				this.allSelect = !this.allSelect
				this.swiperList[this.currentActive].list.forEach(item => {
					this.$set(item, "checked", this.allSelect)
				})
			},
			//单选
			boxItemSelect(item) {
				this.$set(item, "checked", !item.checked)
				if (this.swiperList[this.currentActive].list.filter(item => item.checked).length == this.swiperList[this
						.currentActive].list.length) {
					this.allSelect = true
				} else {
					this.allSelect = false
				}
			},
			//左右滚动
			swiperChange({
				detail: {
					current
				}
			}) {
				this.currentActive = current
				this.$nextTick(()=>{
					this.calcSwiperHeight()
				})
				this.allSelect = false
				if (this.swiperList[this.currentActive].list.length) {
					return
				}
				this.api(this.swiperList[this.currentActive], "/api/member/boxlist")
		
			},
			calcSwiperHeight() {
				console.log("trigger---")
				if (this.currentActive == 0) {
					const query = uni.createSelectorQuery().in(this);
					query.select('#nav').boundingClientRect()
					query.select('#tab').boundingClientRect()
					query.select('#total-placeholder').boundingClientRect()
					query.exec(res => {
						let total = res.reduce((pre, item) => {
							return pre += item.height
						}, 0)
						const window_width = uni.getSystemInfoSync().windowWidth
						const window_height = uni.getSystemInfoSync().windowHeight
						const margin_top = 29 / 750 * window_width
						this.swiperHeight = (window_height - total - margin_top) + "px"
					})
				} else {
					const query = uni.createSelectorQuery().in(this);
					query.select('#nav').boundingClientRect()
					query.select('#tab').boundingClientRect()
					query.exec(res => {
						let total = res.reduce((pre, item) => {
							return pre += item.height
						}, 0)
						const window_width = uni.getSystemInfoSync().windowWidth
						const window_height = uni.getSystemInfoSync().windowHeight
						const margin_top = 29 / 750 * window_width
						this.swiperHeight = (window_height - total - margin_top) + "px"
					})
				}

			}
		},
		onLoad({
			currentActive = 0,
			backType = ""
		}) {
			this.currentActive = parseInt(currentActive)
			this.backType = backType
		},
		async onShow() {
			this.swiperList[this.currentActive].list = []
			this.swiperList[this.currentActive].params.page = 0
			this.swiperList[this.currentActive].loading = false
			this.swiperList[this.currentActive].finish = false
			this.allSelect = false
			await this.api(this.swiperList[this.currentActive], "/api/member/boxlist")
			if(!this.swiperList[this.currentActive].list.length){
				this.calcSwiperHeight()
			}
			else{
				this.$nextTick(()=>{
					this.calcSwiperHeight()
				})
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	page {
		height: 100%;
	}

	.my-box-container {
		/deep/ .uni-popup__wrapper.uni-custom {
			border-top-left-radius: 45rpx;
			border-top-right-radius: 45rpx;

			.uni-popup__wrapper-box {
				border-top-left-radius: 45rpx;
				border-top-right-radius: 45rpx;
				overflow-y: visible;
			}
		}
	}

	.my-box-container /deep/ uni-radio .uni-radio-input-checked {
		background-color: #6E24FF !important;
		border-color: #6E24FF !important;
	}

	.my-box-container {
		height: 100%;

		.swiper {
			margin-top: 29rpx;
			// height: calc(100% - var(--status-bar-height) - 112rpx - 56rpx - 29rpx - 99rpx - constant(safe-area-inset-bottom));
			// height: calc(100% - var(--status-bar-height) - 112rpx - 56rpx - 29rpx - 99rpx - env(safe-area-inset-bottom));

			.scroll-view {
				height: 100%;
			}

			.box-list {
				padding-bottom: 30rpx;
				margin: 0 22rpx 0 19rpx;

				.box-item {
					margin-bottom: 21rpx;

					&:last-child {
						margin-bottom: 0;
					}
				}
			}
		}


		.total-container {
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			box-sizing: content-box;
			z-index: 100;
			background-color: #fff;

			.total-bottom {
				height: 99rpx;
			}

			.free-limit {
				padding-left: 23rpx;
				height: 51rpx;
				background: linear-gradient(90deg, #FF3D56, #FF2AB4);

				.label {
					width: 63rpx;
					height: 28rpx;
					background: #FFFFFF;
					border-radius: 8rpx;
					line-height: 28rpx;
					font-size: 22rpx;
					text-align: center;
					color: #FA2C19;
				}

				.limit-value {
					margin-left: 12rpx;
					color: #FFFFFF;
					font-size: 22rpx;
				}
			}

			.select-all {
				margin-left: 21rpx;
			}

			.radio {
				transform: scale(0.7);
			}

			.label {
				font-size: 25rpx;
				color: #111111;
			}

			.delivery-btn {
				margin-left: auto;
				margin-right: 13rpx;
				width: 215rpx;
				height: 69rpx;
				background: linear-gradient(90deg, #5383FF, #47A3F7);
				box-shadow: 0px 2rpx 8rpx 0px rgba(1, 149, 234, 0.55);
				border-radius: 35rpx;
				line-height: 69rpx;
				text-align: center;
				font-size: 29rpx;
				font-weight: 500;
				color: #FFFFFF;
			}

			.recycling-btn {
				margin-right: 21rpx;
				width: 215rpx;
				height: 69rpx;
				background: linear-gradient(90deg, #9551FF, #A972FF);
				box-shadow: 0px 2rpx 8rpx 0px rgba(149, 81, 255, 0.55);
				border-radius: 35rpx;
				line-height: 69rpx;
				text-align: center;
				font-size: 29rpx;
				font-weight: 500;
				color: #FFFFFF;
			}
		}
	}
	.free-express-dialog{
		padding: 97rpx 67rpx 53rpx;
		position: relative;
		width: 607rpx;
		background: #FFFFFF;
		border-radius: 21rpx;
		box-sizing: border-box;
		.close-icon{
			position: absolute;
			top: 24rpx;
			right: 28rpx;
			font-size: 40rpx;
			color:#333;
		}
		.free-tip{
			margin-bottom: 52rpx;
			font-size: 33rpx;
			font-weight: 400;
			color: #111111;
			text-align: center;
		}
		.think-more{
			width: 230rpx;
			height: 74rpx;
			background: #FFFFFF;
			border: 1rpx solid #6185FF;
			border-radius: 35rpx;
			font-size: 33rpx;
			color: #6185FF;
			line-height: 74rpx;
			text-align: center;
		}
		.continue{
			width: 230rpx;
			height: 74rpx;
			background: linear-gradient(90deg, #6185FF, #8B60FF);
			border-radius: 35rpx;
			font-size: 33rpx;
			color: #fff;
			line-height: 74rpx;
			text-align: center;
		}
	}
</style>
